package com.it.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.admin.service.AdminUserService;
import com.it.common.domain.dos.UserDO;
import com.it.common.enums.ResponseCodeEnum;
import com.it.common.mapper.UserMapper;
import com.it.common.utils.Response;
import com.it.admin.model.dto.user.UpdateAdminUserPasswordDto;
import com.it.admin.model.vo.user.FindUserInfoRspVO;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class AdminUserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements AdminUserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public Response updatePassword(UpdateAdminUserPasswordDto updateAdminUserPasswordDto) {
        String username = updateAdminUserPasswordDto.getUsername();
        String password = updateAdminUserPasswordDto.getPassword();

        password = passwordEncoder.encode(password);

        int count = userMapper.updatePasswordByUsername(username,password);
        return count == 1 ? Response.success() : Response.fail(ResponseCodeEnum.USERNAME_NOT_FOUND);
    }

    public Response findUserInfo(){

        // 获取存储在 ThreadLocal 中的用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        return Response.success(FindUserInfoRspVO.builder().username(username).build());
    }
}
